﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace IveelySE.Dream.Common.Transmission
{
    /// <summary>
    /// 序列化工具
    /// </summary>
    public class Serializer
    {
        /// <summary>
        /// 序列化对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="t">对象</param>
        /// <returns></returns>
        public static byte[] Serialize(Object obj)
        {
            if (obj == null)
                return null;
            System.IO.MemoryStream _memory = new System.IO.MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.TypeFormat = FormatterTypeStyle.TypesAlways;
            formatter.Serialize(_memory, obj);
            _memory.Position = 0;
            byte[] read = new byte[_memory.Length];
            _memory.Read(read, 0, read.Length);
            _memory.Close();
            return read;
        }

        /// <summary>
        /// 反序列化为对象
        /// </summary>
        /// <param name="type">对象类型</param>
        /// <param name="s">对象序列化后的对象</param>
        /// <returns></returns>
        public static object Deserialize(byte[] buffer)
        {
            object _newOjb = null;
            if (buffer == null)
                return _newOjb;
            System.IO.MemoryStream _memory = new System.IO.MemoryStream(buffer);
            _memory.Position = 0;
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.TypeFormat = FormatterTypeStyle.TypesAlways;
            _newOjb = formatter.Deserialize(_memory);
            _memory.Close();
            return _newOjb;
        }
    }
}
